<template>
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import * as echarts from 'echarts';
  
  const chartContainer = ref(null);
  let myChart = null;
  const dataAxis = ref([]); // 用于存储 x 轴数据
  const data = ref([]); // 用于存储 y 轴数据
  
  onMounted(async () => {
    try {
      const response = await fetch('/api/chartdata2');
      const result = await response.json();
      console.log("response", result);
  
      // 从 result.data 中提取数据
      dataAxis.value = result.data.map(item => item.employeeid);
      data.value = result.data.map(item => item.countem);
  
      // 初始化图表
      initChart();
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  });
  
  function initChart() {
    const yMax = 500;
    const dataShadow = new Array(data.value.length).fill(yMax);
  
    myChart = echarts.init(chartContainer.value);
  
    const option = {
      title: {
        text: '员工请假次数统计',
        subtext: '员工ID与请假次数'
      },
      xAxis: {
        data: dataAxis.value,
        axisLabel: {
          inside: true,
          color: '#fff'
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        z: 10
      },
      yAxis: {
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#999'
        }
      },
      dataZoom: [
        {
          type: 'inside'
        }
      ],
      series: [
        {
          type: 'bar',
          showBackground: true,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          data: data.value
        }
      ]
    };
  
    myChart.setOption(option);
  
    const zoomSize = 6;
    myChart.on('click', function (params) {
      console.log(dataAxis.value[Math.max(params.dataIndex - zoomSize / 2, 0)]);
      myChart.dispatchAction({
        type: 'dataZoom',
        startValue: dataAxis.value[Math.max(params.dataIndex - zoomSize / 2, 0)],
        endValue: dataAxis.value[Math.min(params.dataIndex + zoomSize / 2, data.value.length - 1)]
      });
    });
  }
  </script>
  
  <style scoped>
  /* 你可以在这里添加一些样式 */
  </style>